package com.glsx.core.web.controller;

import com.glsx.core.domain.AbstractDomain;
import com.glsx.core.service.BaseService;
import com.glsx.core.web.util.ModelAndViewUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * Controller 常用抽象方法
 * 
 * @author ft
 *
 */
public abstract class AbstractController<T extends AbstractDomain<ID>, S extends BaseService<T, ID>,ID extends Serializable> {

	protected   Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 注入Service
	 * 
	 * @param service
	 * @return
	 */
	@Resource
	private S service;
	
	/**
	 * 页面前辍，<br>
	 * domain名字
	 * 
	 * @return
	 */
	protected abstract String getPagePrex();

	/**
	 * New Domain
	 * 
	 * @return
	 */
	protected abstract T createDomain();

	/**
	 * 添加所需的obj到页面
	 * 
	 * @param model
	 */
	protected abstract void setAttributes(ModelAndView model,T domain);
	
	
	@RequestMapping("add")
	public ModelAndView defaultNew() {
		ModelAndView model = ModelAndViewUtil.newInstance();
		model.setViewName(getPagePrex() + "_edit");
		model.addObject("domain", this.createDomain());
		setAttributes(model,null);
		return model;
	}
	
	@RequestMapping(value="edit/{id}",method = RequestMethod.GET)
	public ModelAndView defaultEdit(@PathVariable ID id) {
		ModelAndView model = ModelAndViewUtil.newInstance();
		model.setViewName(getPagePrex() + "_edit");
		T domain = service.findOne(id);
		model.addObject("domain", domain);
		setAttributes(model,domain);
		return model;
	}

	@RequestMapping(value="list",method = RequestMethod.GET)
	public ModelAndView defaultList(T example, @RequestParam(defaultValue="10")int page, @RequestParam(defaultValue="0")int pageSize) {
		ModelAndView model = ModelAndViewUtil.newInstance();
		model.setViewName(getPagePrex() + "_list");
		Pageable pageable = new PageRequest(page, pageSize);
		Page<T> pageContent = service.findByAuto(example, pageable);
		model.addObject("pageContent", pageContent);
		setAttributes(model,null);
		return model;
	}
}
